class TreeNode {
  constructor(id, pid, parent) {
    this.id = id;
    this.pid = pid;
    this.parent = parent;
    this.children = [];
  }
}

class Forest {
  constructor() {
    this.roots = [];
  }
  init(ele) {
    let success = false;
    for (let index = 0; index < this.roots.length; index++) {
      const element = this.roots[index];
      if (element.pid == ele.id) {
        ele.children.push(element);
        this.roots[index] = ele;
        success = true;
        break;
      } else {
        success = this.addChild(element, ele);
        if (success) {
          break;
        }
      }
    }
    if (!success) {
      this.roots.push(ele);
    }
  }

  sort(arr) {
    if (arr.length > 0 && arr[0].sort !== undefined) {
        arr.sort((pre, cur) => {
          return pre.sort - cur.sort;
        });
        if (arr.children !== undefined && arr.children.length > 0) {
            this.sort(arr.children);
        }
      }
  }

  sortTree() {
    return this.sort(this.roots);
  }

  addChild(parent, ele) {
    if (parent.id == ele.pid) {
    // ele.parent = parent;
      parent.children.push(ele);
    } else {
      let success = false;
      for (let index = 0; index < parent.children.length; index++) {
        const element = parent.children[index];
        success = this.addChild(element, ele);
        if (success) {
          break;
        }
      }
      return success;
    }
    return true;
  }
}
export { TreeNode, Forest };
